package com.heima.wemedia.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.mq.NewsAutoScanConstants;
import com.heima.common.constants.mq.NewsUpOrDownConstants;
import com.heima.common.constants.mq.PublishArticleConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDTO;
import com.heima.model.wemedia.dtos.WmNewsDTO;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVO;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Value("${file.oss.web-site}")
    String webSite;

    @Override
    public ResponseResult findList(WmNewsPageReqDTO dto) {
        //参数检查
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        //如果有文章标题，按照文章标题模糊查询
        wrapper.like(StringUtils.isNoneBlank(dto.getKeyword()),WmNews::getTitle,dto.getKeyword());
        //如果有频道信息，按照频道ID查询
        wrapper.eq(dto.getChannelId()!=null,WmNews::getChannelId,dto.getChannelId());
        //如果有文章状态，按照状态信息进行查询
        wrapper.eq(dto.getStatus()!=null,WmNews::getStatus,dto.getStatus());
        //发布时间 >= 开始时间
        wrapper.ge(dto.getBeginPubDate()!=null,WmNews::getPublishTime,dto.getBeginPubDate());
        // 发布时间 <= 开始时间
        wrapper.le(dto.getEndPubDate()!=null,WmNews::getPublishTime,dto.getEndPubDate());
        //按照登录用户ID去查询
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"请先登录");
        }
        wrapper.eq(WmNews::getUserId,user.getId());
        //按照创建时间降序
        wrapper.orderByDesc(WmNews::getCreatedTime);
        //分页查询，返回结果设置host  地址 为图片访问前缀
        IPage<WmNews> wmNewsPage = new Page<>(dto.getPage(),dto.getSize());
        IPage<WmNews> page = this.page(wmNewsPage, wrapper);
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), page.getTotal());
        result.setData(page.getRecords());
        result.setHost(webSite);
        return result;
    }

    @Autowired
    RabbitTemplate rabbitTemplate;
    /**
     * 自媒体文章发布
     * @param dto
     * @return
     */
    @Transactional
    @Override
    public ResponseResult submitNews(WmNewsDTO dto) {
        //1 检查参数
        if (dto==null||StringUtils.isBlank(dto.getContent())){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章内容不能为空");
        }
        //1.2 检查状态
        if (!WemediaConstants.WM_NEWS_DRAFT_STATUS.equals(dto.getStatus())&&!WemediaConstants.WM_NEWS_SUMMIT_STATUS.equals(dto.getStatus())){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章状态错误");
        }
        //1.3 检查用户是否登录
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"请先登录");
        }
        //封装wmNews
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);
        //type=-1  展示设置为null
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())){
            wmNews.setType(null);
        }
        // 处理dto参数 images封面集合 转换成 字符串
        List<String> images = dto.getImages();
        if (CollectionUtils.isNotEmpty(images)) {
            wmNews.setImages(imageListToStr(images,webSite));
        }
        //设置登录用户
        wmNews.setUserId(user.getId());
        //2 保存或修改文章
        saveOrUpdateWmNews(wmNews);
        //3 设置内容封面与素材关联
        //3.1 抽取文章内容中图片URL路径
        List<String> imageList = parseContentImages(wmNews.getContent());
        //3.2 保存文章内容与素材的关联关系
        if (CollectionUtils.isNotEmpty(imageList)){
            saveRelativeInfo(imageList,wmNews.getId(),WemediaConstants.WM_CONTENT_REFERENCE);
        }
        //3.3 保存文章封面与素材的关联关系
        if (CollectionUtils.isNotEmpty(imageList)){
            saveRelativeInfoCover(dto,imageList, wmNews);
        }
        //发送待审核消息
        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE,wmNews.getId());
        log.info("成功发送 待审核消息 ==> 队列:{}, 文章id:{}",NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE,wmNews.getId());
        return ResponseResult.okResult();
    }

    /**
     * 根据id查询文章
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //参数检查
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询条件
        WmNews wmNews = this.getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //返回结果
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }

    /**
     * 根据id删除文章
     * @param id
     * @return
     */
    @Override
    public ResponseResult delNews(Integer id) {
        //参数检查
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取数据
        WmNews wmNews = this.getById(id);
        //判断文章状态
        if (wmNews.getStatus()==9&&wmNews.getEnable()==1){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章已发布，不能删除");
        }
        //先删除其关联数据
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                .eq(WmNewsMaterial::getNewsId,wmNews.getId()));
        //删除文章数据
        this.removeById(wmNews.getId());
        return ResponseResult.okResult();
    }

    /**
     * 修改上下架
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDTO dto) {
        //参数检查
        if(dto == null || dto.getId() == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        Short enable = dto.getEnable();
        if (enable==9){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"上下架状态错误");
        }
        //查询文章
        WmNews wmNews = this.getById(dto.getId());
        if (wmNews==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //判断文章是否发布
        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章不是发布状态，不能上下架");
        }
        //修改文章状态
        LambdaUpdateWrapper<WmNews> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(WmNews::getEnable,dto.getEnable());
        this.update(wrapper);

        //5. 上下架发送消息通知  用于同步article 及 elasticsearch

        if (wmNews.getArticleId()!=null) {
            if(enable.equals(WemediaConstants.WM_NEWS_UP)){
                // 上架消息
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                        NewsUpOrDownConstants.NEWS_UP_ROUTE_KEY,wmNews.getArticleId());
            }else {
                // 下架消息
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                        NewsUpOrDownConstants.NEWS_DOWN_ROUTE_KEY,wmNews.getArticleId());
            }
        }
        return ResponseResult.okResult();
    }

    @Autowired
    WmNewsMapper wmNewsMapper;
    /**
     * 查询带有文章作者的文章列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult newFindList(NewsAuthDTO dto) {
        //检查参数
        dto.checkParam();
        //记录当前页
        Integer dtoPage = dto.getPage();
        //设置起始页
        dto.setPage((dto.getPage()-1)*dto.getSize());
        //判断是否带有标题,给标题加上通配符
        if (StringUtils.isNotBlank(dto.getTitle())){
            dto.setTitle("%"+dto.getTitle()+"%");
        }
        //连表查询带有作者的文章信息
        List<WmNewsVO> listAndPage = wmNewsMapper.findListAndPage(dto);

        //统计多少条数据
        long count = wmNewsMapper.findListCount(dto);
        //返回结果
        PageResponseResult result = new PageResponseResult(dtoPage, dto.getSize(), count, listAndPage);
        result.setHost(webSite);
        return result;
    }
    @Autowired
    WmUserMapper wmUserMapper;
    /**
     * 查询文章详情
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        //参数检查
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据文章id查询出文章内容
        WmNews wmNews = this.getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //查询作者名称
        WmNews wmNewsAndUser = wmNewsMapper.selectById(wmNews.getUserId());
        //封装返回信息
        WmNewsVO wmNewsVO = new WmNewsVO();
        BeanUtils.copyProperties(wmNews,wmNewsVO);
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVO);
        responseResult.setHost(webSite);
        return responseResult;
    }

    /**
     * 审核文章通过或失败
     * @param status
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(short status, NewsAuthDTO dto) {
        //检查参数
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询文章
        WmNews wmNews = this.getById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //查询文章状态
        Short newsStatus = wmNews.getStatus();
        if (newsStatus.equals(WmNews.Status.PUBLISHED.getCode())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章已发布");
        }
        //修改文章状态
        wmNews.setStatus(status);
        if(StringUtils.isNotBlank(dto.getMsg())){
            wmNews.setReason(dto.getMsg());
        }
        this.updateById(wmNews);
        //通知定时发布文章
        if (status==(short)4){
            // 发布时间
            long publishTime = wmNews.getPublishTime().getTime();
            // 当前时间
            long nowTime = new Date().getTime();
            long remainTime = publishTime - nowTime;
            if(remainTime <= 0){
                // 立即发布
                rabbitTemplate.convertAndSend(PublishArticleConstants.PUBLISH_ARTICLE_EXCHANGE
                        ,PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY
                        ,wmNews.getId()
                );
                log.info("立即发布文章通知成功发送，文章id : {}",wmNews.getId());
            }else {
                // 延时发布
                rabbitTemplate.convertAndSend(PublishArticleConstants.PUBLISH_ARTICLE_EXCHANGE
                        , PublishArticleConstants.PUBLISH_ARTICLE_DEAD_ROUTE_KEY
                        , wmNews.getId()
                        , (message)-> {
                            message.getMessageProperties().setExpiration(String.valueOf(remainTime));
                            return message;
                        }
                );
                log.info("延时发布文章通知成功发送，文章id : {} , 延时时间: {}毫秒",wmNews.getId(),remainTime);
            }
        }
        return ResponseResult.okResult();
    }

    /**
     * 保存文章封面与素材的关系
     * @param dto
     * @param imageList
     * @param wmNews
     */
    private void saveRelativeInfoCover(WmNewsDTO dto, List<String> imageList, WmNews wmNews) {
        //前端用户选择的图
        List<String> images = dto.getImages();
        //如果type为-1,就要从内容中选择图片当封面图
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(wmNews.getType())){
            //文章中图片数量大于2,封面图选取3张
            if (imageList.size()>2){
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images = imageList.stream().limit(3).collect(Collectors.toList());
            }else if (imageList.size()>0&&imageList.size()<=2){
            //文章中图片数量>0,<=2,封面图选取1张
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = imageList.stream().limit(1).collect(Collectors.toList());

            }else {
                //设置无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
                images = null;
            }
            if (CollectionUtils.isNotEmpty(images)){
                //如果自动生成的images不为空,将集合转为字符串拼接
                wmNews.setImages(imageListToStr(images,webSite));
            }
            this.updateById(wmNews);
        }
        //判断最终封面是否为空
        if (CollectionUtils.isNotEmpty(images)){
            //去除前缀
            images = images.stream().map(url -> url.replace(webSite,"")).collect(Collectors.toList());
            saveRelativeInfo(images,wmNews.getId(),WemediaConstants.WM_IMAGE_REFERENCE);
        }
    }

    @Autowired
    WmMaterialMapper wmMaterialMapper;

    /**
     * 保存素材和文章关系
     * @param imageList
     * @param id
     */
    private void saveRelativeInfo(List<String> imageList, Integer id,short type) {
        //根据图片列表及用户id获取素材列表
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(wrapper.in(WmMaterial::getUrl, imageList)
                .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId()));
        //检验素材列表
        if (CollectionUtils.isEmpty(wmMaterials)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"关联的素材信息不存在");
        }
        //将素材列表转为map集合
        Map<String, Integer> urlAndIdMap = wmMaterials.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));
        //判断图片在所有素材中是否存在
        List<Integer> materialIds = new ArrayList<>();
        for (WmMaterial materialUrl : wmMaterials) {
            if (urlAndIdMap.containsKey(materialUrl)){
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"关联的素材信息不存在");
            }
            //收集id
            materialIds.add(urlAndIdMap.get(materialUrl));
        }
        //得到存在的素材id列表,与newid及type进行批量保存
        wmNewsMaterialMapper.saveRelations(materialIds,id,type);
    }

    /**
     * 抽取文章内容中所引用的所有图片
     * @param content
     * @return
     */
    private List<String> parseContentImages(String content) {
        //将json字符串转化成List<Map>集合
        List<Map> mapList = JSONArray.parseArray(content,Map.class);
        // 过滤type=image所有的集合
        return mapList.stream().filter(map -> map.get("type").equals(WemediaConstants.WM_NEWS_TYPE_IMAGE))
                        // 获取到image下的value  图片url
                        .map(map -> (String)map.get("value"))
                        // 获取到image下的value  图片url
                        .map(url -> url.replaceAll(webSite,""))
                        // sretam 转成list集合
                        .collect(Collectors.toList());
    }

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;
    /**
     * 保存或修改文章
     * @param wmNews
     */
    private void saveOrUpdateWmNews(WmNews wmNews){
        wmNews.setCreatedTime(new Date());
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        wmNews.setSubmitedTime(new Date());
        if (wmNews.getId()==null){
            //保存
            wmNews.setCreatedTime(new Date());
            this.save(wmNews);
        }else {
            //修改,需要删除封面与素材的关联
            LambdaQueryWrapper<WmNewsMaterial> wrapper = new LambdaQueryWrapper<>();
            wmNewsMaterialMapper.delete(wrapper.eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            this.updateById(wmNews);
        }
    }
    /**
     * 图片列表转字符串，并去除图片前缀
     * @param images 图片列表
     * @param webSite 图片前缀
     */
    private String imageListToStr(List<String> images, String webSite) {
        return images.stream()  // 获取流
                .map((url) -> url.replace(webSite, ""))  // 对流数据的中间操作
                .collect(Collectors.joining(","));
    }
}
